package com.echronos.thirdsync.mq.AutoCount.receiver;

import com.echronos.thirdsync.mq.AutoCount.handler.AutoCountHandleStrategy;
import com.echronos.thirdsync.mq.AutoCount.message.AutoCountBaseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 消息分发器
 *
 * @Author wangyadong
 * @Date 2025/8/12 15:53
 * @ClassName MessageDispatcher
 */
@Component
public class MessageDispatcher {
    // 存储处理器映射：key=数据类型+操作类型（如"PRODUCT_CREATE"），value=对应的处理器
    private final Map<String, AutoCountHandleStrategy> handlerMap = new ConcurrentHashMap<>();

    // 初始化时注册所有处理器（通过Spring容器注入）
    @Autowired
    public MessageDispatcher(List<AutoCountHandleStrategy> handlers) {
        for (AutoCountHandleStrategy handler : handlers) {
            String key = handler.getDataType() + "_" + handler.getOperationType();
            handlerMap.put(key, handler);
        }
    }

    // 分发消息到对应的处理器
    public void dispatch(AutoCountBaseMessage<?> message) {
        String key = message.getDataType() + "_" + message.getOperationType();
        AutoCountHandleStrategy handler = handlerMap.get(key);
        if (handler == null) {
            throw new UnsupportedOperationException("未找到处理器：" + key);
        }
        // 调用处理器处理消息
        handler.handle(message);
    }
}
